package com.xc.quickstart.job.controller;

import com.xc.quickstart.common.model.ApiResponse;
import com.xc.quickstart.job.BaseJobHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RequestMapping(value = "/job/any/{jobName}")
@Slf4j
@RestController
@Api(description = "任意任务", tags = "job")
public class AnyJobController {

    @Autowired
    private DefaultListableBeanFactory beanFactory;

    @ApiOperation(value = "执行", notes = "执行简单示例任务")
    @RequestMapping(value = "/execute", method = {RequestMethod.POST, RequestMethod.GET})
    public ApiResponse execute(
            @ApiParam("任务名称") @PathVariable("jobName") String jobName,
            @ApiParam("参数") @RequestParam Map<String, String> args) {

        String realJobName = jobName.concat("JobHandler");
        if (!beanFactory.containsBean(realJobName)) {
            return ApiResponse.fail(String.format("没有找到实现,%s", realJobName));
        }

        BaseJobHandler jobHandler = (BaseJobHandler) beanFactory.getBean(realJobName);
        jobHandler.asyncExecute(args);
        return ApiResponse.ok();
    }
}
